package com.cwvs.controller.api;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cwvs.helper.FileUploadHelper;
import com.cwvs.models.ResultInfo;
import com.cwvs.services.AppNeedOrderService;
import com.cwvs.services.AppUserService;
import com.cwvs.utils.AppUtil;
import com.cwvs.utils.Pages;

@Controller
@RequestMapping("/api/need")
public class AppNeedOrderController {
	@Resource
	private AppUserService appUserService;
	@Resource
	private AppNeedOrderService appNeedOrderService;
	@Resource
	private FileUploadHelper fileUploadHelper;
	private static Logger logger = Logger
			.getLogger(AppNeedOrderController.class.getName());

	/**
	 * 需求发布
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/add")
	public @ResponseBody
	ResultInfo add(HttpServletRequest request, HttpServletResponse response) {
		ResultInfo res = new ResultInfo();
		Map<String, Object> map = new HashMap<String, Object>();
		Enumeration paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					map.put(paramName.toUpperCase(),
							paramValue.replaceAll("[\\t\\n\\r]", ""));
				}
			}
		}
		String token = request.getParameter("token");
		if (StringUtils.isBlank(token)) {
			res.setMessage("无效的登录信息");
			return res;
		}
		res = appUserService.getUserInfo(token);
		if (!res.isSuccess()) {
			return res;
		}
		try {
			String picUrl = fileUploadHelper.imageFileUpload(request, "image",
					AppUtil.getIntNow(), 3, 640, 406,false,false);
			if (StringUtils.isBlank(picUrl)) {
				res.setResCode("0");
				res.setSuccess(false);
				res.setResult(null);
				res.setMessage("需求发布失败");
				logger.error("需求图片上传失败");
				return res;
			}
			map.put("PIC_URL", picUrl);
			map.put("STATUS", 3);
			map.put("STATUS_NAME", "待支付");
			String id = appNeedOrderService.add(map);
			if (StringUtils.isBlank(id)) {
				res.setResCode("0");
				res.setSuccess(false);
				res.setResult(null);
				res.setMessage("需求发布失败");
				return res;
			} else {
				res.setResCode("0");
				res.setSuccess(true);
				res.setResult(id);
				res.setMessage("发布成功");
				return res;
			}
		} catch (Exception e) {
			e.printStackTrace();
			res.setResCode("0");
			res.setSuccess(false);
			res.setResult(null);
			res.setMessage("需求发布失败");
			logger.error(e.getMessage());
			return res;
		}
	}

	/**
	 * 获取需求信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/info")
	public @ResponseBody
	ResultInfo info(HttpServletRequest request, HttpServletResponse response) {
		ResultInfo res = new ResultInfo();
		Map<String, Object> map = new HashMap<String, Object>();
		Enumeration paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					map.put(paramName.toUpperCase(),
							paramValue.replaceAll("[\\t\\n\\r]", ""));
				}
			}
		}
		Map<String, Object> info = appNeedOrderService.getInfoById(map);
		if (null == info || info.isEmpty()) {
			res.setMessage("无效的需求信息");
			res.setResult(null);
			res.setResCode("0");
			res.setSuccess(false);
			return res;
		}
		res.setMessage("获取成功");
		res.setSuccess(true);
		info.put("NEED_PAY", false);
		info.put("IS_SHOW", false);
		String token = request.getParameter("token");
		if (StringUtils.isNotBlank(token)) {
			ResultInfo res1 = appUserService.getUserInfo(token);
			if (res1.isSuccess()) {
				Map<String, Object> user = (Map<String, Object>) res1
						.getResult();
				if (StringUtils.equalsIgnoreCase(
						MapUtils.getString(user, "USER_ID"),
						MapUtils.getString(info, "USER_ID"))) {
					if (MapUtils.getIntValue(info, "STATUS") == 3) {
						info.put("NEED_PAY", true);
					}
				} else {
					if (MapUtils.getIntValue(info, "STATUS") == 5) {
						info.put("IS_SHOW", true);
					}

				}
			}
		}
		res.setResult(info);
		return res;
	}

	/**
	 * 接受需求
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/accept")
	public @ResponseBody
	ResultInfo accept(HttpServletRequest request, HttpServletResponse response) {
		ResultInfo res = new ResultInfo();
		Map<String, Object> map = new HashMap<String, Object>();
		Enumeration paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					map.put(paramName.toUpperCase(),
							paramValue.replaceAll("[\\t\\n\\r]", ""));
				}
			}
		}
		String token = request.getParameter("token");
		if (StringUtils.isBlank(token)) {
			res.setMessage("无效的登录信息");
			return res;
		}
		res = appUserService.getUserInfo(token);
		if (!res.isSuccess()) {
			return res;
		}
		Map<String, Object> user = (Map<String, Object>) res.getResult();
		Map<String, Object> info = appNeedOrderService.getInfoById(map);
		if (null == info || info.isEmpty()) {
			res.setMessage("无效的需求信息");
			res.setResult(null);
			res.setResCode("0");
			res.setSuccess(false);
			return res;
		}
		if (StringUtils.equalsIgnoreCase(MapUtils.getString(user, "USER_ID"),
				MapUtils.getString(info, "USER_ID"))) {
			res.setMessage("需求不可接");
			res.setResult(null);
			res.setResCode("0");
			res.setSuccess(false);
			return res;
		}
		if (MapUtils.getIntValue(info, "STATUS") != 5) {
			res.setMessage("需求不可接");
			res.setResult(null);
			res.setResCode("0");
			res.setSuccess(false);
			return res;
		}
		map.put("USER_ID", MapUtils.getString(user, "USER_ID"));
		if (appNeedOrderService.isExists(map)) {
			res.setMessage("您已揭榜过");
			res.setResult(null);
			res.setResCode("0");
			res.setSuccess(false);
			return res;
		}
		map.put("STATUS", 1);
		map.put("STATUS_NAME", "揭榜中");
		if (appNeedOrderService.saveAcceptInfo(map)) {
			res.setMessage("保存成功");
			res.setResult(null);
			res.setResCode("0");
			res.setSuccess(true);
			return res;
		}
		res.setMessage("保存失败");
		res.setResult(null);
		res.setResCode("0");
		res.setSuccess(false);
		return res;
	}

	/**
	 * 需求列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/need_list")
	public @ResponseBody
	ResultInfo needList(HttpServletRequest request,
			HttpServletResponse response) {
		ResultInfo res = new ResultInfo();
		res.setSuccess(true);
		res.setMessage("查询成功");
		res.setResCode("0");
		Map<String, Object> map = new HashMap<String, Object>();
		Enumeration paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					map.put(paramName.toUpperCase(),
							paramValue.replaceAll("[\\t\\n\\r]", ""));
				}
			}
		}
		map.put("STATUS", "5,6");
		Pages page = new Pages();
		page.setCurrentPage(StringUtils.isBlank(request.getParameter("page")) ? 1
				: Integer.parseInt(request.getParameter("page")));
		page = appNeedOrderService.needList(map, page);
		res.setResult((List<Map<String, Object>>) page.getPage());
		return res;
	}

	/**
	 * 用户需求列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/user_need")
	public @ResponseBody
	ResultInfo userNeed(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		Enumeration paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					map.put(paramName.toUpperCase(),
							paramValue.replaceAll("[\\t\\n\\r]", ""));
				}
			}
		}
		String token = MapUtils.getString(map, "TOKEN");
		ResultInfo res = appUserService.getUserInfo(token);
		if (!res.isSuccess()) {
			return res;
		}

		Map<String, Object> info = (HashMap<String, Object>) res.getResult();
		res.setMessage("查询成功");
		res.setSuccess(true);
		Pages page = new Pages();
		page.setCurrentPage(StringUtils.isBlank(request.getParameter("page")) ? 1
				: Integer.parseInt(request.getParameter("page")));
		map.put("USER_ID", MapUtils.getString(info, "USER_ID"));
		map.remove("STATUS");
		page = appNeedOrderService.needList(map, page);
		res.setResult((List<Map<String, Object>>) page.getPage());
		return res;
	}
	
	/**
	 * 用户揭榜列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/user_accept")
	public @ResponseBody
	ResultInfo userAccept(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		Enumeration paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					map.put(paramName.toUpperCase(),
							paramValue.replaceAll("[\\t\\n\\r]", ""));
				}
			}
		}
		String token = MapUtils.getString(map, "TOKEN");
		ResultInfo res = appUserService.getUserInfo(token);
		if (!res.isSuccess()) {
			return res;
		}

		Map<String, Object> info = (HashMap<String, Object>) res.getResult();
		res.setMessage("查询成功");
		res.setSuccess(true);
		Pages page = new Pages();
		page.setCurrentPage(StringUtils.isBlank(request.getParameter("page")) ? 1
				: Integer.parseInt(request.getParameter("page")));
		map.put("USER_ID", MapUtils.getString(info, "USER_ID"));
		map.remove("STATUS");
		page = appNeedOrderService.acceptList(map, page);
		res.setResult((List<Map<String, Object>>) page.getPage());
		return res;
	}
	

}
